package cn.yunyichina.provider.base.service.impl;

import cn.yunyichina.provider.base.dao.MedicalCardDao;
import cn.yunyichina.provider.base.dao.PersonalUserDao;
import cn.yunyichina.provider.base.dao.ZhyySourceDao;
import cn.yunyichina.provider.base.entity.MedicalCard;
import cn.yunyichina.provider.base.utils.DruidUtil;
import cn.yunyichina.provider.base.utils.OrgCodeMap;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.iface.entity.PersonalUser;
import cn.yunyichina.provider.iface.entity.base.HospitalOutVo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.fy.util.Record;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("medicalcardServiceImpl")
public class MedicalCardServiceImpl extends BaseSelectService {
    private static final Logger logger = LoggerFactory.getLogger(MedicalCardServiceImpl.class);

    @Autowired
    private MedicalCardDao medicalCardDao;
    @Autowired
    private PersonalUserDao personalUserDao;

    /**
     * 查询诊疗卡
     * @param strJson 对应数据库字段名
     * @return
     */
    public List<MedicalCard> selectMedicalCard(String strJson) {
    	return super.listEntity(strJson, MedicalCard.class, medicalCardDao);
    }

    public MedicalCard getByCardNo(String strJson) {

    	JSONObject jsonObj = JsonUtils.parseObject(strJson);

    	return medicalCardDao.getMedicalCardByCardNo(jsonObj.getString("orgCode"),jsonObj.getString("medicalCardNo"),jsonObj.getShortValue("medicalCardType"));
    }
    /**
     * 根据诊疗卡号查询用户。用于消息发送
     * yyt.base.medicalcard.by.cardno.get

     */
    public Response getMedicalCardByCardNo(String strJson, String sessionId,String appId) {
        logger.info("根据诊疗卡号查询用户 原始入参 strJson={}",strJson);
        Response response = new Response();
    	JSONObject jsonObj = JsonUtils.parseObject(strJson);
        String hospitalCode = jsonObj.getString("org_code");
        String medicalCardNo = jsonObj.getString("medical_card_no");
        String openId = jsonObj.getString("open_id");
        MedicalCard cardVo = null;
        Map<String, String> extMap = new HashMap<String, String>();
        extMap.put("app_code",appId);

        boolean oldPlatformFlag = true;
        //查询缓存中所有的医院
        logger.info("查询医院缓存入参 extMap={}",new Object[]{JsonUtils.toJsonString(extMap)});
        Response hospitalResp =  BaseService.callUnderlineFromInternal("yyt.base.hospital.by.app.code.list",JsonUtils.toJsonString(extMap));
        logger.info("缓存的医院列表 hospitalResp={}",new Object[]{JsonUtils.toJsonString(hospitalResp)});
        if ("0".equals(hospitalResp.getResultCode())){
            List<HospitalOutVo> hospitalOutVoList = JsonUtils.parseArray(hospitalResp.getResult(),HospitalOutVo.class);
            if (CollectionUtils.isNotEmpty(hospitalOutVoList)){
               logger.info("缓存的医院列表 hospitalOutVoList = {} ",new Object[]{JsonUtils.toJsonString(hospitalOutVoList)});
                for (HospitalOutVo hospitalOutVo :hospitalOutVoList){
                    if (hospitalCode.equals(hospitalOutVo.getHospitalCode())&&hospitalOutVo.getOldPlatformFlag() !=null&&hospitalOutVo.getOldPlatformFlag()!=1){
                        oldPlatformFlag = false;
                        break;
                    }
                }
            }
        }



        if (oldPlatformFlag){
            logger.info("拿卡走旧库");
            try (Connection con = DruidUtil.getConnection();
                 Statement stmt = con.createStatement()) {

                String table = "biz_medical_card_";

                StringBuilder sb = new StringBuilder("select * from (");

                for (int i = 1 ;i<=10 ;i++) {
                    sb.append("select * from ").append(table).append(i).append("  where card_no = '")  .append(medicalCardNo).append("'");
                    sb.append(" and state =1 ");
                    sb.append(" and card_type = '").append(jsonObj.getShortValue("medicalCardType")).append("'");
                    if (OrgCodeMap.hospitalCodeMap.get(hospitalCode) !=null){
                        sb.append(OrgCodeMap.hospitalCodeMap.get(hospitalCode) );
                    }else {
                        sb.append(" and hospital_code = '").append(hospitalCode).append("'");
                    }
                    if (i !=10){
                        sb.append(" UNION ");
                    }
                }

                sb.append(") as allCard");

                String sql = sb.toString();

                logger.info("Sql ="+sql);


                try (ResultSet rs = stmt.executeQuery(sql)) {
                    if (null != rs) {
                        while (rs.next()) {
                            cardVo = new MedicalCard();
                            cardVo.setId(rs.getString("ID"));

                            cardVo.setOrgCode(rs.getString("HOSPITAL_CODE"));
                            cardVo.setOrgName(rs.getString("HOSPITAL_NAME"));
                            cardVo.setMedicalCardType(Short.valueOf(rs.getString("CARD_TYPE")));
                            cardVo.setMedicalCardNo(rs.getString("CARD_NO"));
                            cardVo.setPatName(rs.getString("NAME"));
                            cardVo.setPatMobile(rs.getString("MOBILE"));
                            cardVo.setIdCardType(Short.valueOf(rs.getString("ID_TYPE")));
                            cardVo.setIdCardNo(rs.getString("ID_NO"));
                            cardVo.setPatId(rs.getString("USER_ID"));
                        }
                    }
                }
            } catch (SQLException e) {
                response.setResultCodeAndMessage("1001","查询旧库失败");
                logger.error("[DBUtil -> SQLException]", e);
                return response;
            }
        }else {
            logger.info("拿卡走新库");
            MedicalCard queryMedicalCard = new MedicalCard();
            PersonalUser personalUser = null;
            if (StringUtils.isNotEmpty(openId)) {
                personalUser = personalUserDao.selectPersonalUserByOpenId(openId);
                if (personalUser == null) {
                    logger.error("通过openId ={} 换取userId 失败", openId);
                    response.setResultCodeAndMessage("1001","通过openId ={} 换取userId 失败");
                    return response;
                }
                queryMedicalCard.setUserId(personalUser.getId());
            }
            queryMedicalCard.setMedicalCardNo(medicalCardNo);
            queryMedicalCard.setOrgCode(hospitalCode);
            List<MedicalCard> medicalCardList = medicalCardDao.select(queryMedicalCard);
            logger.info("查询数据库 medicalCardList={}",new Object[]{JsonUtils.toJsonString(medicalCardList)});
            if (CollectionUtils.isNotEmpty(medicalCardList)){
                cardVo = medicalCardList.get(0);
                response.setResultCodeAndMessageAndResult("0","成功",JsonUtils.toJsonString(cardVo));
                return response;
            }

        }
        response.setResultCodeAndMessageAndResult("0","成功",JsonUtils.toJsonString(cardVo));
        logger.info("根据诊疗卡号查询用户 cardVo ={}",new Object[]{JsonUtils.toJsonString(cardVo)});
        return response;
    }

    /**
     * 根据诊疗卡号查询用户。用于消息发送
     * yyt.base.medicalcard.by.cardno.new.get
	   @return MedicalCard,可能返回null，如果数据库异常，则会抛出异常
     */
    public MedicalCard getMedicalCardByCardNoNew(String strJson) {

    	try(ZhyySourceDao dao = new ZhyySourceDao()) {

			JSONObject jsonObj = JsonUtils.parseObject(strJson);

		    String table = "biz_medical_card_";

		    String hospitalCode = jsonObj.getString("org_code");

	        StringBuilder sb = new StringBuilder("select * from (");

	        for (int i = 1 ;i<=10 ;i++){
	            sb.append("select * from ").append(table).append(i).append("  where card_no = '")  .append(jsonObj.getString("medicalCardNo")).append("'");
	            sb.append(" and state =1 ");
	            sb.append(" and card_type = '").append(jsonObj.getShortValue("medicalCardType")).append("'");
	            if (OrgCodeMap.hospitalCodeMap.get(hospitalCode) !=null){
	                sb.append(OrgCodeMap.hospitalCodeMap.get(hospitalCode) );
	            }else {
	                sb.append(" and hospital_code = '").append(hospitalCode).append("'");
	            }
	            if (i !=10){
	                sb.append(" UNION ");
	            }
	        }

	        sb.append(") as allCard");

		    String sql = sb.toString();

		    logger.info("Sql ="+sql);

		    Record rd = dao.selectOne(sql);
		    if (rd != null) {
		    	return JsonUtils.parseObject(rd,MedicalCard.class);
		    }

			return null;

		} catch (CallException ce) {
			logger.error("getMedicalCardByCardNoNew内部异常",ce);
			throw ce;
		} catch (Exception e) {
			logger.error("getMedicalCardByCardNoNew异常",e);
			throw new CallException("-1", "获取智慧医院诊疗卡信息异常");
		}

    }

    /**
     * 根据ID查询用户。用于消息发送
     * yyt.base.medicalcard.by.id.get
     * @return 找不到返回null
     */
    public MedicalCard getMedicalCardById(String data) {

    	MedicalCard MedicalCard = JsonUtils.parseObject(data, MedicalCard.class);

    	List<MedicalCard> listMedicalCard =  medicalCardDao.select(MedicalCard);
    	if (listMedicalCard.size() > 0) {
    		return listMedicalCard.get(0);
    	}
    	return null;
    }

    /**
     * 根据AppId和卡号查询用户
     * yyt.base.medicalcard.by.cardno.and.appid.get
     * @param data
     * @return
     */
    public MedicalCard getMedicalcardByCardnoAndAppid(String data){
        Map<String,String> dataMap=JsonUtils.parseObject(data,Map.class);
        List<MedicalCard> listMedicalCard=medicalCardDao.selectMedicalcardByCardnoAndAppid(dataMap.get("card_no"),dataMap.get("app_id"));
        if (listMedicalCard.size() > 0) {
            return listMedicalCard.get(0);
        }
        return null;
    }

    /**
     * 更新
     * yyt.base.medicalcard.by.id.update
     * @param
     * @param data
     */
    public void updateMedicalCardById(String data) {
    	MedicalCard MedicalCard = JsonUtils.parseObject(data, MedicalCard.class);
    	medicalCardDao.update(MedicalCard);

    }

    public  void updatePatientInfoByPatId(String data){
        MedicalCard MedicalCard = JsonUtils.parseObject(data, MedicalCard.class);
        medicalCardDao.updatePatientInfoByPatId(MedicalCard);
    }

}
